//
//  MKKeyedArchiver.swift
//  Fanmugua
//
//  Created by MK on 2021/3/28.
//  Copyright © 2021 taolang. All rights reserved.
//

import UIKit

// 主文件夹名称
let MK_FOLDER_NAME:String = "MKKit"

class MKKeyedArchiver: NSObject {
    
    ///归档文件
    class func archiver(folderName:String!, fileName:String!, object:AnyObject){
        var path:String = DOCUMENT_DIR_PATH + "/\(MK_FOLDER_NAME)/\(folderName!)"
        if creatFile(path: path) {
            path += "/\(fileName!)"
            NSKeyedArchiver.archiveRootObject(object, toFile: path)
        }
    }
    
    /// 解档文件
    class func unarchiver(folderName:String!, fileName:String!) ->AnyObject? {
        let path = DOCUMENT_DIR_PATH + "/\(MK_FOLDER_NAME)/\(folderName!)/\(fileName!)"
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as AnyObject?
    }
    
    /// 是否存在归档文件
    class func isExist(folderName:String!, fileName:String? = nil) ->Bool {
        var path = DOCUMENT_DIR_PATH + "/\(MK_FOLDER_NAME)/\(folderName!)"
        if (fileName != nil && !fileName!.isEmpty) {
            path += "/\(fileName!)"
        }
        return FileManager.default.fileExists(atPath: path)
    }
    
    /// 清空归档文件
    class func clear() -> Bool {
        let path = DOCUMENT_DIR_PATH + "/\(MK_FOLDER_NAME)"
        do{
            try FileManager.default.removeItem(atPath: path)
            return true
        }catch{ }
        return false
    }
    
    /// 创建文件夹,如果存在则不创建
    private class func creatFile(path:String) ->Bool {
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: path) {
            return true
        }
        
        do{
            try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            return true
        }catch{ }
        
        return false
    }
}
